package service

import (
	"encoding/json"
	"fmt"
	"choujiang/common/db"
	"choujiang/common/models"
	"choujiang/common/utils"
)

const (
	GOODS_LIST_CASH_KEY = "BoxKey::leyouboxgoodscash"
)

type GoodsDetail struct {
	Id           int64     `json:"id"`
	Title        string    `json:"title"`
	Desc         string    `json:"desc"`
	Price        int64     `json:"price"`
	Cover        string    `json:"cover"`
	Num          int       `json:"num"`
	Type         int64     `json:"type"`
	Balance      int64     `json:"balance"`
	Imgs         []Picture `json:"imgs"`
	Pictures     []Picture `json:"pictures"`
	LimitPeople  int64     `json:"limit_people"`
	CurPeople    int64     `json:"cur_people"`
	CouponStatus int64     `json:"coupon_status"`
	CouponAt     int64     `json:"coupon_at"`
	UserAvatar   []string  `json:"user_avatar"`
}

type Picture struct {
	Url string `json:"url"`
}

type JoinDetail struct {
	CouponSlice  []string `json:"coupon_slice"`  //券码切片
	CouponNumber int      `json:"coupon_number"` //券码数量
	Probability  float64  `json:"probability"`   //中奖概率
}

func GetGoodsList() ([]model.Goods, error) {
	goods := make([]model.Goods, 0)
	var err error
	err = db.MysqlEngine.Where("is_show=?", 1).Desc("order").Find(&goods)
	for i := 0; i < len(goods); i++ {
		goods[i].Cover = utils.AddPrefix(goods[i].Cover)
		goods[i].MyCoupon = GetMyCoupon(goods[i].Id)
	}

	return goods, err
}

func GetGoodsDetail(Id int64) (GoodsDetail, error) {
	reGoods := GoodsDetail{}
	goods := new(model.Goods)
	_, err := db.MysqlEngine.ID(Id).Get(goods)
	reGoods.Id = goods.Id
	reGoods.Title = goods.Title
	reGoods.Desc = goods.Desc
	reGoods.Price = goods.Price
	reGoods.Cover = utils.AddPrefix(goods.Cover)
	reGoods.Num = goods.Num
	reGoods.Type = goods.Type
	reGoods.Balance = goods.Balance
	reGoods.Pictures = PackagePicture(goods)
	reGoods.Imgs = PackageImages(goods)
	reGoods.CouponAt = goods.CouponAt
	reGoods.CouponStatus = goods.CouponStatus
	reGoods.LimitPeople = goods.LimitPeople
	reGoods.CurPeople = goods.CurPeople
	reGoods.UserAvatar = CouponUserAvatar(goods, 7)
	return reGoods, err
}

func PackagePicture(goods *model.Goods) []Picture {
	var imgSlice []Picture
	jsonString := goods.Pictures
	json.Unmarshal([]byte(jsonString), &imgSlice)
	for i := 0; i < len(imgSlice); i++ {
		imgSlice[i].Url = utils.AddPrefix(imgSlice[i].Url)
	}
	return imgSlice
}

func PackageImages(goods *model.Goods) []Picture {
	var imgSlice []Picture
	jsonString := goods.Banners
	json.Unmarshal([]byte(jsonString), &imgSlice)
	for i := 0; i < len(imgSlice); i++ {
		imgSlice[i].Url = utils.AddPrefix(imgSlice[i].Url)
	}
	return imgSlice
}

func GetMyCoupon(goodsId int64) int {
	coupon := make([]model.GoodsCoupon, 0)
	err := db.MysqlEngine.Where("goods_id=?", goodsId).Find(&coupon)
	if err != nil {
		fmt.Printf("-----Err[GetMyCoupon] err: %s", err)
	}
	return len(coupon)
}

//获取抽奖用户的头像
func CouponUserAvatar(goods *model.Goods, num int64) []string {
	reStr := make([]string, 0)
	ugl := make([]model.UserGoodsLog, 0)
	err := db.MysqlEngine.Where("goods_id=?", goods.Id).OrderBy("created_at").Find(&ugl)
	if err != nil {
		fmt.Printf("-----[CouponUserAvatar] err: %s", err)
	}
	if len(ugl) > 0 {
		for i := 0; i < len(ugl); i++ {
			reStr = append(reStr, ugl[i].HeadImgUrl)
		}
	}
	return reStr
}

//获取我的抽奖参与详情
func MyParticipateDetail(userId, goodsId int64) *JoinDetail {
	gp := make([]model.GoodsCoupon, 0)
	err := db.MysqlEngine.Where("goods_id=? and user_id=?", goodsId, userId).Find(&gp)
	if err != nil {
		fmt.Printf("-----[MyParticipateDetail] err: %s", err)
	}
	couponSlice := make([]string, 0)
	if len(gp) > 0 {
		for i := 0; i < len(gp); i++ {
			couponSlice = append(couponSlice, gp[i].Code)
		}
	}
	totalGp := make([]model.GoodsCoupon, 0)
	err = db.MysqlEngine.Where("goods_id=?", goodsId).Find(&totalGp)
	if err != nil {
		fmt.Printf("-----[MyParticipateDetail] err: %s", err)
	}
	var probability float64
	if len(totalGp) > 0 {
		probability = float64(len(gp)) / float64(len(totalGp)) * 100
	}
	reDetail := &JoinDetail{
		CouponSlice:  couponSlice,
		CouponNumber: len(couponSlice),
		Probability:  utils.CutDecimal(probability),
	}
	return reDetail
}
